<template>
    <div class="viewer-container">
        <!--地图-->
        <!-- <mars-map :url="configUrl" @onload="onMapload" /> -->
    </div>
</template>

<script>
// import MarsMap from '@/components/mars-work/mars-map.vue'
// import * as mars3d from 'mars3d'
import LivePlayer from '@liveqing/liveplayer'
// const Cesium = mars3d.Cesium

let tiles3dLayer;
let mapIns;

export default {
    name: 'ThreeJsViewer',
    components: {
        LivePlayer
    },
    data() {
        const basePathUrl = window.basePathUrl || ''
        return {
            configUrl: basePathUrl + 'config/config.json'
        };
    },
    mounted() {

    },
    beforeDestroy() {

    },
    methods: {
        // 地图构造完成回调
        onMapload(map) {
            mapIns = map
            // 以下为演示代码
            //经度:121.772167,纬度:31.164893,
            map.setCameraView({ lat: 31.164893, lng: 121.772167, alt: 600, heading: 337.6, pitch: -37 })

            // 创建entity图层
            const graphicLayer = new this.mars3d.layer.GraphicLayer()
            map.addLayer(graphicLayer)
            //新添加
            map.fixedLight = true // 固定光照，避免gltf模型随时间存在亮度不一致。

            // 固定光照时间
            map.clock.currentTime = Cesium.JulianDate.fromDate(new Date("2022-11-01 12:00:00"))
            // map.clock.shouldAnimate = false

            // 固定光照方向
            map.scene.light = new Cesium.DirectionalLight({
                direction: map.scene.camera.direction
            })
            map.camera.percentageChanged = 0.001
            map.on(mars3d.EventType.cameraChanged, function (event) {
                map.scene.light.direction = map.scene.camera.direction
            })

          

            // 调试面板
            map.viewer.extend(Cesium.viewerCesiumInspectorMixin)
            map.scene.globe.depthTestAgainstTerrain = true

            // 针对不同终端的优化配置
            if (this.isPCBroswer()) {
                // Cesium 1.61以后会默认关闭反走样，对于桌面端而言还是开启得好，
                map.scene.postProcessStages.fxaa.enabled = true

                // 鼠标滚轮放大的步长参数
                map.scene.screenSpaceCameraController._zoomFactor = 2.0

                // IE浏览器优化
                if (window.navigator.userAgent.toLowerCase().indexOf("msie") >= 0) {
                    map.viewer.targetFrameRate = 20 // 限制帧率
                    map.viewer.requestRenderMode = true // 取消实时渲染
                }
            } else {
                // 鼠标滚轮放大的步长参数
                map.scene.screenSpaceCameraController._zoomFactor = 5.0

                // 移动设备上禁掉以下几个选项，可以相对更加流畅
                map.viewer.requestRenderMode = true // 取消实时渲染
                map.scene.fog.enabled = false
                map.scene.skyAtmosphere.show = false
                map.scene.globe.showGroundAtmosphere = false
            }

            const type = mars3d.Util.getRequestByName("data")

            switch (type) {
                case "qx-shequ":
                    showQxShequDemo()
                    break
                case "qx-simiao":
                    showQxSimiaoDemo()
                    break
                case "jzw-hefei":
                    showJzwHefeiDemo()
                    break
                case "max-shihua":
                    showMaxShihuaDemo()
                    break
                case "bim-qiaoliang":
                    showBimQiaoliangDemo()
                    break
                case "bim-ditiezhan":
                    showBimDitiezhanDemo()
                    break
                case "pnts-ganta":
                    showPntsGantaDemo()
                    break
                default:
                    // this.showMaxShihuaDemo()
                    break
            }

            // 2.在layer上绑定监听事件
            graphicLayer.on(this.mars3d.EventType.click, function (event) {
                console.log('监听layer，单击了矢量对象', event)
            })
            graphicLayer.on(this.mars3d.EventType.mouseOver, function (event) {
                console.log('监听layer，鼠标移入了矢量对象', event)
            })
            graphicLayer.on(this.mars3d.EventType.mouseOut, function (event) {
                console.log('监听layer，鼠标移出了矢量对象', event)
            })

            // 可在图层上绑定popup,对所有加到这个图层的矢量数据都生效
            // graphicLayer.bindPopup('我是layer上绑定的Popup', {
            //   anchor: [0, -10]
            // })

            // 可在图层绑定右键菜单,对所有加到这个图层的矢量数据都生效
            graphicLayer.bindContextMenu([
                {
                    text: '删除对象',
                    iconCls: 'fa fa-trash-o',
                    callback: function (e) {
                        const graphic = e.graphic
                        if (graphic) {
                            graphicLayer.removeGraphic(graphic)
                        }
                    }
                }
            ])

            // 加一些演示数据，来源 http://mars3d.cn/editor-vue.html?id=layer-graphic/basis/entity
            //添加墙体
            this.addDemoGraphic1(graphicLayer);
            this.addDemoGraphic2(graphicLayer);
            // this.bindLayerDemo2();
            //添加摄像头1
            //经度:121.770033,纬度:31.170985
            this.addRandomGraphicByCount(graphicLayer, [121.769971, 31.171028, 33.3])

        },
        //显示摄像机
        showVido() {
            document.getElementById("mars3d-divCameraPoint-content").style.display = "block";
            document.getElementById("mars3d-divCameraPoint-line").style.display = "block"
            document.getElementById("mars3d-divCameraPoint-point").style.display = "block"
        },

        hideVido() {
            document.getElementById("mars3d-divCameraPoint-content").style.display = "none";
            document.getElementById("mars3d-divCameraPoint-line").style.display = "none"
            document.getElementById("mars3d-divCameraPoint-point").style.display = "none"
        },

        addRandomGraphicByCount(graphicLayer, position) {
            const graphicImg = new mars3d.graphic.DivGraphic({
                position,
                style: {
                    html: ` <div class="mars3d-divCameraPoint-content" id="mars3d-divCameraPoint-content">
                      <img style="width:30px;height:30px;"  class="mars3d-divCameraPoint-img" src="//data.mars3d.cn/img/marker/svg/camera.svg" >
                    </div>
                    <div class="mars3d-divCameraPoint-line" id="mars3d-divCameraPoint-line" style="height: 120px;width: 5px;margin-top: 10px;border-left: 3px dashed #5b8fee;margin-left: calc(50% - 1px);"></div>
                    <div class="mars3d-divCameraPoint-point" id="mars3d-divCameraPoint-point" style="border-radius: 50%;width: 8px;height: 8px;margin-left: calc(50% - 3px);background-color: #5b8fee;"></div>
                  `,
                    offsetX: -16,
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 100000)
                },
                popup: '<video src="http://data.mars3d.cn/file/video/lukou.mp4" style="width:250px"></video>',
                popupOptions: {
                    offsetY: -170, // 显示Popup的偏移值，是DivGraphic本身的像素高度值
                    template: `<div class="marsBlackPanel">
                        <div class="marsBlackPanel-text">{content}</div>
                        <span class="mars3d-popup-close-button closeButton">×</span>
                      </div>`,
                    horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
                    verticalOrigin: Cesium.VerticalOrigin.CENTER
                }
            })
            graphicLayer.addGraphic(graphicImg)
        },

        removeLayer() {
            if (tiles3dLayer) {
                mapIns.basemap = 2021 // 切换到默认影像底图
                mapIns.removeLayer(tiles3dLayer, true)
                tiles3dLayer = null
            }
        },
        addDemoGraphic1(graphicLayer) {
            // 走马灯围墙效果
            const scrollWall = new mars3d.graphic.ScrollWall({

                positions: [
                    [
                        121.767321,
                        31.172264,
                        15.9
                    ],
                    [
                        121.768163,
                        31.16994,
                        17.6
                    ],
                    [
                        121.773867,
                        31.171456,
                        16.6
                    ],
                    [
                        121.773012,
                        31.173606,
                        16.4
                    ],
                    [
                        121.770018,
                        31.172733,
                        17.5
                    ],
                    [
                        121.769904,
                        31.17297,
                        17.6
                    ],
                    [
                        121.769892,
                        31.172967,
                        17.6
                    ]

                ],
                style: {
                    diffHeight: 20, // 高度
                    color: "#2a5caa",
                    speed: 10,
                    reverse: false, // 方向：true往上、false往下
                    label: {
                        text: "",
                        font_size: 18,
                        color: "#2a5caa",
                        show: false
                    },
                    // 高亮时的样式（默认为鼠标移入，也可以指定type:'click'单击高亮），构造后也可以openHighlight、closeHighlight方法来手动调用
                    highlight: {
                        color: "#2a5caa",
                        label: {
                            show: true
                        }
                    }
                },
                attr: { remark: "示例1", xiaoguo: "鼠标移入时展示高亮效果" }
            })
            graphicLayer.addGraphic(scrollWall)
        },

        addDemoGraphic2(graphicLayer) {
            // 走马灯围墙效果
            const scrollWall = new mars3d.graphic.ScrollWall({

                positions: [
                    [
                        121.770821,
                        31.172946,
                        17.2
                    ],
                    [
                        121.77162,
                        31.170863,
                        17.8
                    ]

                ],
                style: {
                    diffHeight: 20, // 高度
                    color: "#ffe600",
                    speed: 10,
                    reverse: false, // 方向：true往上、false往下
                    label: {
                        text: "",
                        font_size: 18,
                        color: "#ffe600",
                        show: false
                    },
                    // 高亮时的样式（默认为鼠标移入，也可以指定type:'click'单击高亮），构造后也可以openHighlight、closeHighlight方法来手动调用
                    highlight: {
                        color: "#ffe600",
                        label: {
                            show: true
                        }
                    }
                },
                attr: { remark: "示例1", xiaoguo: "鼠标移入时展示高亮效果" }
            })
            graphicLayer.addGraphic(scrollWall)
        },


        showMaxShihuaDemo() {
            this.removeLayer()

            tiles3dLayer = new mars3d.layer.TilesetLayer({
                name: "石化工厂",
                // url: "//data.mars3d.cn/3dtiles/max-shihua/tileset.json",
                url: "./resource/mars3d/tileset.json",
                axis: undefined,
                // position: { lng: 117.077158, lat: 31.659116, alt: -2.0 },
                rotation: {
                    x: 0.0,
                    y: 0.0,
                    z: -19.0
                },
                scale: 1,
                depthTestAgainstTerrain: true,
                position: { lng: 121.769469, lat: 31.171548, alt: 40.1 },
                maximumScreenSpaceError: 1,
                // shadows: Cesium.ShadowMode.DISABLED,
                // 以下参数可以参考用于3dtiles总数据大，清晰度过高情况下进行性能优化。这不是一个通用的解决方案，但可以以此为参考。
                skipLevelOfDetail: true,
                loadSiblings: true,
                cullRequestsWhileMoving: true,
                cullRequestsWhileMovingMultiplier: 10,
                preferLeaves: true,
                preloadWhenHidden: true,
                enableDebugWireframe: true, // 是否可以进行三角网的切换显示
                // 以上为优化的参数

                // popup: "all",
                highlight: {
                    type: mars3d.EventType.click, // 默认为鼠标移入高亮，也可以指定click单击高亮
                    outlineEffect: true, // 采用OutlineEffect方式来高亮
                    color: "#00FF00",
                    width: 6
                },
                // /经度:121.773652,纬度:31.169559,
                //经度:121.772167,纬度:31.164893,
                center: { lat: 31.164893, lng: 121.772167, alt: 600, heading: 337.1, pitch: -37 },
                flyTo: true
            })
            mapIns.addLayer(tiles3dLayer)

            // 可以绑定Popup弹窗，回调方法中任意处理
            tiles3dLayer.bindPopup(function (event) {
                const attr = event.graphic.attr
                // attr["视频"] = `<video src='http://data.mars3d.cn/file/video/lukou.mp4' controls autoplay style="width: 300px;" ></video>`;
                return mars3d.Util.getTemplateHtml({ title: "石化工厂", template: "all", attr })
            })

            // 单击事件
            tiles3dLayer.on(mars3d.EventType.click, function (event) {
                console.log("单击了3dtiles图层", event)
            })
        },

        isPCBroswer() {
            const sUserAgent = navigator.userAgent.toLowerCase()

            const bIsIpad = sUserAgent.match(/ipad/i) === "ipad"
            const bIsIphoneOs = sUserAgent.match(/iphone/i) === "iphone"
            const bIsMidp = sUserAgent.match(/midp/i) === "midp"
            const bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) === "rv:1.2.3.4"
            const bIsUc = sUserAgent.match(/ucweb/i) === "ucweb"
            const bIsAndroid = sUserAgent.match(/android/i) === "android"
            const bIsCE = sUserAgent.match(/windows ce/i) === "windows ce"
            const bIsWM = sUserAgent.match(/windows mobile/i) === "windows mobile"
            if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
                return false
            } else {
                return true
            }
        },
    }
};
</script>

<style scoped>
.viewer-container {
    width: 100vw;
    height: 100vh;
    overflow: hidden;
}

canvas {
    display: block;
}

.loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    font-size: 24px;
}
</style>